var formChild = null;
var _cheked = false;

$(function(){
    var _mode = "";
    var _membre = "";

    $("#cboseccion").change(function(){
        var _id = parseInt($(this).val())-2;
        document.location = './?ws=Sections&id='+ _id.toString()
    });

    /* JQUERY_EXTEND */
    $.extend({ 		
        uploadFile : function(_folder, _sizeLimit, _multi){
            var current_file = "";
			
            $("#fileUpload").uploadify({   
                uploader: './Resouces/js/uploader/uploadify.swf',   
                cancelImg: './Resouces/js/uploader/cancel.png',   
                folder: _folder,   
                buttonText: 'Parcourir',
                checkScript: './Resouces/js/uploader/check.php',  
                width:114,
                height:35,
                fileDesc: "Format de l'image *.jpg uniquement",
                fileExt: '*.jpg',
				
                sizeLimit: _sizeLimit,
                script: './Resouces/js/uploader/uploadify.php',   
                multi: _multi,   
                simUploadLimit: 1, 
                auto: true,
                'queueID'        : 'fileQueue',
				
                onProgress: function(event,queueID,fileObj,data){
                    current_file = queueID;
                },
                onSelect: function(event,queueID,fileObj){
                    _newname =  fileObj.name;
                    $('#lbl-okfile').css('display','none');
                },
                onError: function(event,queueID,fileObj,errorObj){
                    iconError(false,"Error.");
                },
                onComplete: function(event,queueID,fileObj,response,data){				
                    _newname = fileObj.name;
                    
                    $.insertImage( $('#txtURL').val(), _membre, _newname );	
                },
                onAllComplete: function(event,data){
                    iconError(false,"Image(s) ajout&eacute;(s)");
                }
            });   
			
        },
		
        // PHOTOS
        initPhotos : function(){
            $("#jqGrid").jqGrid({
                // <MODIFICAR>
                url: './Queries/query-photos.php?id='+_intUserSV+'nd='+new Date().getTime(),
                colNames:['int_id_gallery','Titre de la galerie', 'Nombres de photos', 'Etat'],
                colModel:[
                {
                    hidden:true, 
                    search:false, 
                    name:'int_id_gallery', 
                    index:'int_id_gallery', 
                    align:'left'
                },

                {
                    name:'var_title_gallery', 
                    index:'var_title_gallery', 
                    align:'left'
                },

                {
                    name:'int_num_photos', 
                    index:'int_num_photos', 
                    align:'center'
                },

                {
                    search:false, 
                    name:'var_htmldesc', 
                    index:'var_htmldesc', 
                    align:'left'
                }
                ],
                sortname: ['int_id_gallery'],
                sortorder: "desc",
                width: 746,
                height: 240,
                // </MODIFICAR>
				
                onSelectRow: function(ids) {
                    var gr = $("#jqGrid").getGridParam('selrow');
	
                    if( gr != null ){			
                        $.getPhoto(ids);
                        $("#jqGrid2").setGridParam({
                            url: "./Queries/query-images.php?id="+ids+"&nd="+new Date().getTime(),
                            page:1
                        });
                        $("#jqGrid2").trigger('reloadGrid');		
                    }
                },
                loadComplete: function(xhr){
                    if(_mode=="insert" || _mode=="charger" || _mode=="update"){
                        $('#jqGrid').setSelection(_membre);
                    }
                }
                ,
                loadtext: 'Chargement..',
                datatype: "json",
                pager: $('#jqpager'),
                rowNum:25,
                rowList:[25,50,75],	
                viewrecords: true,
                multiselect: false
            });
			
            $("#jqGrid2").jqGrid({
                // <MODIFICAR>
                url: './Queries/query-images.php?q=1&id=-1',
                colNames:['int_id_image','', 'Noms des photos'],
                colModel:[
                {
                    hidden:true, 
                    search:false, 
                    name:'int_id_image', 
                    index:'int_id_image', 
                    align:'left'
                },

                {
                    name:'var_name_image_html', 
                    sortable: false, 
                    index:'var_name_image_html',
                    width:10, 
                    align:'center'
                },

                {
                    name:'var_name_image', 
                    index:'var_name_image', 
                    align:'left'
                }
                ],
                sortname: ['int_id_image'],
                sortorder: "desc",
                width: 746,
                height: 340,
                // </MODIFICAR>

                loadtext: 'Chargement..',
                datatype: "json",
                pager: $('#jqpager2'),
                rowNum:50,
                rowList:[50,100,150],	
                viewrecords: true,
                multiselect: true,
                loadComplete: function(xhr){
                    if(_mode=="deletephotos"){
                        $('#jqGrid').trigger('reloadGrid');
                        _mode = '';
                    }
                }
            });
        }, 
        insertPhotos : function(_var_title_gallery,_int_num_photos, _var_path_gallery, _int_id_sections_view, _int_id_state){
            $.post("./?ws=Photos&act=insertGallery", {
                _var_title_gallery:_var_title_gallery,
                _int_num_photos:_int_num_photos, 
                _var_path_gallery:_var_path_gallery, 
                _int_id_sections_view:_int_id_sections_view, 
                _int_id_state:_int_id_state, 
                cache:new Date().getTime()
            }, function(data){
                if($.trim(data)!=""){
                    _membre = $.trim(data);																																																																																																						
                    alert("Donn\u00E9es sauvegarder avec succ\u00E8s.");
                    /*if(confirm("Voulez-vous ajouter des photos \u00E1 la galerie?")){
						_membre = $.trim(data);
						$.modal.close();
						UploadFrame(_membre);
					}*/
                    $('#jqGrid').trigger('reloadGrid');
                    $.modal.close();
                }
            });
        },
        updatePhotos : function(_id,_var_title_gallery, _int_id_sections_view, _int_id_state){
            $.post("./?ws=Photos&act=updateGallery", {
                _id:_id, 
                _var_title_gallery:_var_title_gallery, 
                _int_id_sections_view:_int_id_sections_view, 
                _int_id_state:_int_id_state, 
                cache:new Date().getTime()
            }, function(data){
                if($.trim(data)!=""){
                    $('#jqGrid').trigger('reloadGrid');
                    alert( $.trim(data) );
                    $.modal.close();
                }
                else $.modal.close();
            });
        },
        getPhoto : function(_id){
            $.post("./?ws=Photos&act=getGallery", {
                _id:_id, 
                cache:new Date().getTime()
            }, function(data){
                if($.trim(data)!=""){
                    var _data = Array();																																																																																																																				
                    _data = data.split('_%_');
                    $("#tl-views-photos").text( " : "+$.trim(_data[0]) );
                    $('#txtdescription').val( $.trim(_data[0]) ); 
                    $('#txtURL').val( $.trim(_data[1]) ); 
                    selectCbo('#cboetat',$.trim(_data[2]) );
                }
            });
        },
        deletePhotos : function(_ids){
            $.post("./?ws=Photos&act=deleteGallery", {
                _ids:_ids, 
                cache:new Date().getTime()
            }, function(data){
                if($.trim(data)!=""){
                    alert(data);
                    _mode = 'deletephotos';
                    $('#jqGrid2').trigger('reloadGrid');
                }
            });
        },
        initImages : function(idGallery){
            $.getPhoto(idGallery);
        },
        insertImage : function(_pathGallery,_int_id_gallery, _nameimage){
            $.post("./?ws=Images&act=insertImages", {
                _pathGallery:_pathGallery,
                _int_id_gallery:_int_id_gallery, 
                _nameimage:_nameimage, 
                cache:new Date().getTime()
            }, function(data){
                if($.trim(data)!=""){		
                //$("#ifr-images").attr('src', "./Views/iframe/getImages.php?qs="+_membre+"&ref="+$('#txtURL').val()+"&id="+Math.random());
                }
            });
        },
        deleteImages : function(_ids,_pathGallery){
            $.post("./?ws=Images&act=deleteImages", {
                _ids:_ids,
                _pathGallery:_pathGallery, 
                cache:new Date().getTime()
            }, function(data){																											 
                if($.trim(data)!=""){																																																							
                    //$("#ifr-images").attr('src', "./Views/iframe/getImages.php?qs="+_membre+"&ref="+$('#txtURL').val()+"&id="+Math.random());
                    alert(data);
                    $('#jqGrid2').trigger('reloadGrid');
                }
            });
        }
    // END PHOTOS

    });
    /* END JQUERY_EXTEND */
	
    function validateForm(){
        $('#txtdescription').select();
        _form = $("#frm-lien").validate({
            event: "blur",
            rules:{ 
                'txtdescription': "required",
                'cboetat': "required"	
            },
            messages:{
                'txtdescription': "Entrez le titre de la galerie.",
                'cboetat': "S&eacute;lectionnez l'&eacute;tat."
            }
        });	
		
        function disabledControls(val){
            if(val){
                $('#txtdescription').attr('disabled','-1'); 
                $('#cboetat').attr('disabled','-1');
            }
            else{
                $('#txtdescription').removeAttr('disabled'); 
                $('#cboetat').removeAttr('disabled');

                $("#btn-save").removeAttr('disabled');
            }
        }

        // SAVE FORM
        $("#frm-lien").submit(function(){
            if(_form.valid()){
                disabledControls(true);
                if(_mode == "update"){
                    disabledControls(false);
                    $.updatePhotos( _membre,  $('#txtdescription').val(), _intUserSV, $('#cboetat').val() );
                }
                else{
                    $.insertPhotos( $('#txtdescription').val(), 0, "",_intUserSV, $('#cboetat').val() );
                }	
            }
			
            return false;
        });
    };
	
    function selectCbo(_idcbo, _intval){
        $(_idcbo+" option").each(function (){
            if($(this).val() == _intval){
                $(this).attr('selected','selected'); 
            }
        });
    }
	
    $("#btn-cancel").click( function(){
        $.modal.close();
    });
	
    $("#btn-terminer").click( function(){
        $.modal.close();
    });
    $("#btn-annuler").click( function(){
        $.modal.close();
    });
	
    $("#sinsert").click( function(){
        _mode = "insert";
        $('#Nouveau-title').html("Ajouter une galerie"); 
        selectCbo('#cboetat',"" );
        $('#txtdescription').val('');
		
        $("#Nouveau").modal({
            position: [0,0],
            opacity: 25,
            autoResize: true,
            onOpen: function (dialog){
                dialog.overlay.fadeIn('fast', function (){
                    dialog.container.fadeIn('fast', function (){
                        dialog.data.show();
                        validateForm();
                    });
                });
            }			
        });
    });
	
    $("#supdate").click(function(){
        var gr = $("#jqGrid").getGridParam('selrow');
        _mode = "update";
		
        $('#Nouveau-title').html("Modifier la galerie");
        switch(gr)
        {
            case null:
                alert('Avertissement!\nS\u00E9lectionnez une galerie parmi la liste.');
                break;
			
            default:
                _membre = gr;
                $.getPhoto( _membre );
                $("#Nouveau").modal({
                    position: [0,0],
                    opacity: 45,
                    autoResize: true,
                    onOpen: function (dialog){
                        dialog.overlay.fadeIn('fast', function (){
                            dialog.container.fadeIn('fast', function (){
                                dialog.data.show();
                                validateForm();
                            });
                        });
                    }			
                });
                break;
			
        /*default:
				alert('Avertissement\nSeulement un photo \u00E1 la fois.');
			break;*/
        }
    });

    $("#sdelete").click(function(){
        if(_intUserT == 1){
            _mode = 'delete';
            var gr = $("#jqGrid").getGridParam('selrow');
	
            if( gr != null ){
                /*var s = $("#jqGrid").getGridParam('selarrrow');
				var f = s.toString();
				var j =  f.split(',');*/

                if(confirm("Eliminer galerie\nVous avez selection\u00E9 galerie.\nVoulez vous vraiment l'effacer(s)?")){
                    $.deletePhotos(gr);
                }
            }
            else{
                alert('Avertissement\nS\u00E9lectionnez une galerie \u00E0 effacer.');
            }
        }
    });

    $("#scharger").click(function(){
        var gr = $("#jqGrid").getGridParam('selrow');
        _mode = "charger";

        switch(gr)
        {
            case null:
                alert('Avertissement!\nS\u00E9lectionnez une galerie parmi la liste.');
                break;
			
            default:
                _membre = gr;
                $.getPhoto( _membre );
                $("#UploadImage").modal({
                    position: [0,0],
                    opacity: 45,
                    autoResize: true,
                    onOpen: function (dialog){
                        dialog.overlay.fadeIn('fast', function (){
                            dialog.container.fadeIn('fast', function (){
                                dialog.data.show();
                                $.uploadFile( '/csme.fr/galeries/'+$('#txtURL').val()+'/view', '3000000', true );
                            });
                        });
                    },
                    onClose: function (dialog){
						
                        $('#jqGrid2').trigger('reloadGrid');	
                        $('#jqGrid').trigger('reloadGrid');
                        $.modal.close();
                    }	
                });
                break;
        /*
			default:
				alert('Avertissement\nSeulement un photo \u00E1 la fois.');
			break;*/
        }
    });
	
    function iconError(_bool, _title){
        $('#lbl-okfile').css('display','none');
        var _icon = "";
        if(_bool) _icon = './Resouces/images/cancelfield.png';
        else _icon = './Resouces/images/okfield.png';
		
        $('#lbl-okfile').html('<img src="'+_icon+'" alt="'+_title+'" title="'+_title+'" />');
        $('#lbl-okfile').fadeIn();
    }
	
    $("#btn-cancel2").click(function(){
        $.modal.close();
    });

    $("#sschekall").click(function(){
        SelectingChekbox(formChild);
    });
	
    $("#ssdelete").click(function(){
        var gr = $("#jqGrid2").getGridParam('selrow');

        if( gr != null ){
            var s = $("#jqGrid2").getGridParam('selarrrow');
            var f = s.toString();
            var j =  f.split(',');

            if(confirm("Eliminer Photo(s)\nVous avez selection\u00E9 "+j.length+" photo(s).\nVoulez vous vraiment l'effacer(s)?")){
                $.deleteImages(f,$('#txtURL').val());
            }
        }
        else{
            alert('Avertissement\nS\u00E9lectionnez les photos \u00E0 effacer.');
        }
    });

    $('#sselt').click(function(){
        $('#jqGrid').setSelection('2');
    });
	
    //Initializing
    $.initPhotos();
    if(_sectSel!=0) selectCbo("#cboseccion",_sectSel); 
});